package uk.co.chrisdadswell.radioreminder;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SpinnerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Christian Dadswell
 * Date: 21/03/13
 * Time: 14:00
 */

/*
To execute async -
    getAllStations = new GetStations();
    getAllStations.execute();
*/

public class fragmentBroadcasts extends ListFragment {
    OnBroadcastSelectedListener mCallback;
    GetBroadcasts getBroadcastsByUrl;
    static final String APP_TAG = "rr: ";
    static final String ACT_TAG = "fragmentBroadcasts: ";
    final static String ARG_POSITION = "position";
    static String stationSelected = null;
    static String stationScheduleUrl = null;
    int mCurrentPosition = -1;
    static LinkedHashMap<String, String> lhmBroadcasts = null;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnBroadcastSelectedListener {
        /** Called by stationsFragment when a list item is selected */
        public void onBroadcastSelected(String broadcastSelected);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(APP_TAG, ACT_TAG + "... OnAttach ....");
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnBroadcastSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnBroadcastSelectedListener");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(APP_TAG, ACT_TAG + "... OnCreate ....");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(APP_TAG, ACT_TAG + "... OnCreateView ....");
        setHasOptionsMenu(true); // used to give the activity an action bar specific to this fragment
        stationSelected = getArguments().getString(constants.STATION_NAME);
        stationScheduleUrl = getArguments().getString(constants.STATION_SCHEDULE_URL);

        // If activity recreated (such as from screen rotate), restore
        // the previous article selection set by onSaveInstanceState().
        // This is primarily necessary when in the two-pane layout.
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }

        // onCreateView() is a lifecycle event that is unique to a Fragment. This is called when Android
        // needs the layout for this Fragment. The call to LayoutInflater::inflate() simply takes the layout
        // ID for the layout file, the parent view that will hold the layout, and an option to add the inflated
        // view to the parent. This should always be false or an exception will be thrown. Android will add
        // the view to the parent when necessary.
        View view = inflater.inflate(R.layout.fragment_broadcasts, container, false);

        // This is how you access your layout views. Notice how we call the findViewById() method
        // on our View directly. There is no method called findViewById() defined on Fragments like
        // there is in an Activity.
        //ListView list_Broadcasts = (ListView) view.findViewById(R.id.list_broadcasts);

        // Setup ActionBar spinner for station types
        SpinnerAdapter mSpinnerAdapter;
        mSpinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.broadcast_dates, android.R.layout.simple_spinner_dropdown_item);

        // Setup ActionBar
        ActionBar actionBar = getActivity().getActionBar();
        //actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.));
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar_underline)));
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ActionBar.OnNavigationListener navigationListener = new ActionBar.OnNavigationListener() {

            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId) {
                //listBroadcasts.clear();
                switch(itemPosition) {
                    case 0: //
                        break;
                }
                return false;
           }
        };

        /** Setting dropdown items and item navigation listener for the actionbar */
        getActivity().getActionBar().setListNavigationCallbacks(mSpinnerAdapter, navigationListener);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(APP_TAG, ACT_TAG + "... OnActivityCreated ....");
        ArrayList<HashMap<String, String>> broadcastLists = new ArrayList<HashMap<String, String>>();
        // display the listview items... somehow
        //lhmBroadcasts = GetBroadcastsHashMapFromFile(constants.broadcastStationsDir, ReturnShortStationName());

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(APP_TAG, ACT_TAG + "... OnStart ....");
        // During startup, check if there are arguments passed to the fragment.
        // onStart is a good place to do this because the layout has already been
        // applied to the fragment at this point so we can safely call the method
        // below that sets the article text.
        Bundle args = getArguments();
        if (args != null) {
            // get passed in station name
            updateBroadcastsList(args.getInt(constants.STATION_NAME));
        } else if (mCurrentPosition != -1) {
            // Set article based on saved instance state defined during onCreateView
            updateBroadcastsList(mCurrentPosition);
        }


    }

    private void updateBroadcastsList(int position) {
        mCurrentPosition = position;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(APP_TAG, ACT_TAG + "... OnResume ....");

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Save the current broadcast selection in case we need to recreate the fragment
        outState.putInt(ARG_POSITION, mCurrentPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        String selectedBroadcast = (String) l.getItemAtPosition(position);
        if (mCallback != null) {
            mCallback.onBroadcastSelected(selectedBroadcast);
        }

        // TWO PANE LAYOUT NOTE
        // Set the item as checked to be highlighted when in two-pane layout
        //getListView().setItemChecked(position, true);
    }

    // Optional actionbar menu items
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.stations_menu, menu);
    }

    // Async task to get broadcasts to json if required
    class GetBroadcasts extends AsyncTask<Void, Integer, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // do the stuff here
            //GetBroadcastsByUrl();
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            //Toast.makeText(activityDashboard.this,"Stations downloaded", Toast.LENGTH_SHORT).show();
        }
    }

    public void GetTodaysBroadcastsByUrl() {
        if(isInternetOn()) {
            // need to get stationame, url and todays date
            //functions_Parser.GetBroadcastsForStationByUrl();
        }else{
            // Dialog needed
        }
    }

    public void GetBroadcastsByDate() {
        if(isInternetOn()) {
            // need to get stationame, url and todays date
            //functions_Parser.GetBroadcastsForStationByUrl();
        }else{
            // Dialog needed
        }
    }

    // CHECK INTERNET METHOD
    public final boolean isInternetOn() {
        Log.d(APP_TAG, ACT_TAG + "Checking connectivity ...");
        ConnectivityManager connec = null;
        connec =  (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        if ( connec != null){
            NetworkInfo result = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (result != null && result.isConnectedOrConnecting());
            return true;
        }
        return false;
    }
}